
var fs = require('fs');
var path = require('path');
var file_util = require('./file_util')
//需要被移动到resource下的bundle。
var folderList = ['lobby','decoration','outdoor']
//源目录
var asset_path = process.argv[2];
//目标目录
var export_dir = process.argv[3];
//是否是bundle 1和0
var opt = process.argv[4];



function getBundleName(name){
	for(var i = 0; i < folderList.length; i ++){
		let s = folderList[i]
		if(name.indexOf(s) >= 0){
			return s;
		}
	}
	return null;
}

function setBundle(meta_name,opt){
	console.log(' meta_name',meta_name,' opt ',opt)
	var flag = opt == '1' ? true : false;
	console.log(' flag ',flag)
	let fileData = file_util.readFile(meta_name)
	if(fileData){
		var obj = JSON.parse(fileData);
		obj['isBundle'] = flag
		console.log('fileData 2222 ',JSON.stringify(obj))
		file_util.writeFile(meta_name,JSON.stringify(obj))
	}
}


function exchangeFiles(asset_path,export_dir,opt) {
	var stat = fs.statSync(asset_path);
	if (!stat.isDirectory()) {
		return;
	}
	var subpaths = fs.readdirSync(asset_path),
		subpath;
	for (var i = 0; i < subpaths.length; ++i) {
		if (subpaths[i][0] === '.') {
			continue;
		}
		subpath = path.join(asset_path, subpaths[i]);
		console.log(" subpath ", subpath);
		var fname = getBundleName(subpath)
		if(fname){
			stat = fs.statSync(subpath);
				//修改meta中的boundle 属性
				//移动整个文件夹到resource中。
			if (stat.isDirectory()) {
				let dest_path = path.join(export_dir,fname) 
				file_util.mkdir(dest_path)
				file_util.copyDir(subpath,dest_path)
				file_util.delDir(subpath)		
			}else{
				var meta_name = subpath
				var exportMeta_name = path.join(export_dir,fname)+'.meta'
				setBundle(meta_name,opt)
				file_util.copyFile(meta_name,exportMeta_name)
				file_util.deleteFile(meta_name)
			}
		}
	}
}
exchangeFiles(asset_path,export_dir,opt)
